<template>
  <view class="friends-container">
    <!-- 轻提示：WS重连中 -->
    <view v-if="reconnecting" class="alert-banner reconnecting">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    
    <!-- 轻提示：达到最大重连次数 -->
    <view v-if="maxAttemptsReached" class="alert-banner error">
      <view class="alert-content">
        <text>⚠️</text>
        <text>连接失败次数过多，请手动重试</text>
      </view>
      <button @click="manualRetryConnection" class="retry-small-btn">重试</button>
    </view>
    
    <!-- 在线状态：显示好友列表 -->
    <view v-if="isServerOnline">
      <!-- 搜索和操作组件 -->
      <SearchAndActions 
        :searchKeyword="searchKeyword"
        :pendingRequestsCount="pendingRequestsCount"
        :isLoading="isLoading"
        @search="handleSearch"
        @add-friend="navigateToAdd"
        @view-requests="navigateToRequests"
        @refresh="refreshFriends"
        @view-chats="navigateToChatList"
      />
      
      <!-- 好友统计组件 -->
      <FriendsStats 
        :totalFriends="totalFriends"
        :onlineFriends="onlineFriends"
        :recentFriends="recentFriends"
      />
      
      <!-- 好友列表 -->
      <view class="friends-list">
        <view class="section-title">
          <text class="title-text">我的好友</text>
        </view>
        
        <!-- 空状态 -->
        <view v-if="filteredFriends.length === 0" class="empty-state">
          <text class="empty-icon">👥</text>
          <text class="empty-title">暂无好友</text>
          <text class="empty-desc">快去添加一些好友吧！</text>
          <button class="empty-action-btn" @click="navigateToAdd">
            <text class="btn-text">添加好友</text>
          </button>
        </view>
        
        <!-- 好友卡片列表 -->
        <FriendCard 
          v-for="friend in filteredFriends" 
          :key="friend.id"
          :friend="friend"
          @click="openChat(friend)"
          @chat="openChat(friend)"
          @options="showFriendOptions(friend)"
        />
      </view>
    </view>
    
    <!-- 离线状态组件 -->
    <OfflineStatus 
      v-else
      @retry="retryConnection"
    />

    <!-- 好友选项弹窗组件 -->
    <FriendOptionsModal 
      :visible="showFriendOptionsModal"
      @close="closeFriendOptions"
      @start-chat="startChat"
      @view-profile="viewProfile"
      @remove-friend="removeFriend"
    />
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import chatService from '@/utils/websocket-chat-service.js'
import appStateManager from '@/utils/app-state-manager.js'
import SearchAndActions from './components/SearchAndActions.vue'
import FriendsStats from './components/FriendsStats.vue'
import FriendCard from './components/FriendCard.vue'
import OfflineStatus from './components/OfflineStatus.vue'
import FriendOptionsModal from './components/FriendOptionsModal.vue'

export default {
  components: {
    SearchAndActions,
    FriendsStats,
    FriendCard,
    OfflineStatus,
    FriendOptionsModal
  },
  data() {
    return {
      isServerOnline: false,
      searchKeyword: '',
      friends: [],
      pendingRequestsCount: 0,
      showFriendOptionsModal: false,
      selectedFriend: null,
      isLoading: false,
      reconnecting: false,
      maxAttemptsReached: false,
      wsConnected: false,
      healthOk: false,
      offlineGraceTimer: null
    }
  },
  
  computed: {
    filteredFriends() {
      if (!this.searchKeyword) {
        return this.friends.sort((a, b) => {
          if (a.isOnline && !b.isOnline) return -1
          if (!a.isOnline && b.isOnline) return 1
          return new Date(b.lastMessageTime) - new Date(a.lastMessageTime)
        })
      }
      
      const keyword = this.searchKeyword.toLowerCase()
      return this.friends.filter(friend => 
        friend.name.toLowerCase().includes(keyword) ||
        (friend.status && friend.status.toLowerCase().includes(keyword))
      )
    },
    
    totalFriends() {
      return this.friends.length
    },
    
    onlineFriends() {
      return this.friends.filter(friend => friend.isOnline).length
    },
    
    recentFriends() {
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000)
      return this.friends.filter(friend => 
        friend.lastMessageTime && new Date(friend.lastMessageTime) > oneDayAgo
      ).length
    }
  },
  
  onLoad() {
    console.log('好友列表页面加载')
    
    const serverState = appStateManager.getState('server')
    this.isServerOnline = serverState.isOnline
    
    appStateManager.subscribe('server', (serverState) => {
      this.isServerOnline = serverState.isOnline
      if (serverState.isOnline) {
        this.loadFriends()
      }
    })
    
    this.loadFriendsFromLocal()
    this.initWsForOnline()
    
    if (this.isServerOnline) {
      setTimeout(() => {
        this.loadFriendsFromServer().catch(error => {
          console.error('从服务器加载好友列表失败:', error)
        })
      }, 500)
    }
  },
  
  onShow() {
    const serverState = appStateManager.getState('server')
    this.isServerOnline = serverState.isOnline
    
    appStateManager.refreshServerStatus().then(isOnline => {
      if (isOnline) {
        this.loadFriends()
      }
    })
    
    if (chatService.isConnected) {
      this.refreshOnlineStatus()
    }
  },
  
  onUnload() {
    this.cleanup()
  },
  
  onPullDownRefresh() {
    this.loadFriends().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    // ========== 搜索相关 ==========
    handleSearch(keyword) {
      this.searchKeyword = keyword
    },
    
    // ========== 导航方法 ==========
    navigateToAdd() {
      uni.navigateTo({ url: '/pages/friends/add/add' })
    },
    
    navigateToRequests() {
      uni.navigateTo({ url: '/pages/friends/requests/requests' })
    },
    
    navigateToChatList() {
      uni.navigateTo({ url: '/pages/chat/list' })
    },
    
    openChat(friend) {
      uni.navigateTo({
        url: `/pages/chat/chat?userId=${friend.id}&userName=${friend.name}`
      })
    },
    
    // ========== 好友选项 ==========
    showFriendOptions(friend) {
      this.selectedFriend = friend
      this.showFriendOptionsModal = true
    },
    
    closeFriendOptions() {
      this.showFriendOptionsModal = false
      this.selectedFriend = null
    },
    
    startChat() {
      if (this.selectedFriend) {
        this.openChat(this.selectedFriend)
        this.closeFriendOptions()
      }
    },
    
    viewProfile() {
      if (this.selectedFriend) {
        uni.navigateTo({
          url: `/pages/friends/detail/detail?friendId=${this.selectedFriend.id}`
        })
        this.closeFriendOptions()
      }
    },
    
    async removeFriend() {
      if (!this.selectedFriend) return
      
      uni.showModal({
        title: '删除好友',
        content: `确定要删除好友 ${this.selectedFriend.name} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await apiService.removeFriend(this.selectedFriend.id)
              uni.showToast({ title: '已删除好友', icon: 'success' })
              this.loadFriends()
              this.closeFriendOptions()
            } catch (error) {
              console.error('删除好友失败:', error)
              uni.showToast({ title: '删除失败', icon: 'error' })
            }
          }
        }
      })
    },
    
    // ========== 数据加载 ==========
    async loadFriends() {
      this.isLoading = true
      try {
        await this.loadFriendsFromServer()
      } catch (error) {
        console.error('加载好友列表失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    async refreshFriends() {
      await this.loadFriends()
      if (chatService.isConnected) {
        this.refreshOnlineStatus()
      }
    },
    
    loadFriendsFromLocal() {
      try {
        const storedFriends = uni.getStorageSync('friends_list')
        if (storedFriends) {
          this.friends = JSON.parse(storedFriends)
          console.log('从本地加载好友列表:', this.friends.length, '个')
        }
      } catch (error) {
        console.error('从本地加载好友列表失败:', error)
      }
    },
    
    async loadFriendsFromServer() {
      try {
        const response = await apiService.getFriendsList()
        if (response.code === 'SUCCESS' && response.data) {
          this.friends = response.data.friends || []
          uni.setStorageSync('friends_list', JSON.stringify(this.friends))
          console.log('从服务器加载好友列表:', this.friends.length, '个')
        }
      } catch (error) {
        console.error('从服务器加载好友列表失败:', error)
        throw error
      }
    },
    
    // ========== WebSocket 相关 ==========
    async initWsForOnline() {
      try {
        if (!chatService.isConnected) {
          await chatService.init()
        }
        
        chatService.onStatusChange((info) => {
          const st = info?.status
          if (st === 'connected') {
            this.wsConnected = true
            this.reconnecting = false
            this.loadFriendsFromServer().catch(() => {})
          } else if (st === 'disconnected' || st === 'error') {
            this.wsConnected = false
            this.reconnecting = false
            this.markAllFriendsOffline()
          } else if (st === 'reconnecting') {
            this.reconnecting = true
            this.maxAttemptsReached = false
          }
        })
        
        chatService.onFriendOnlineStatus((data) => {
          this.updateFriendOnlineStatus(data.userId, data.isOnline)
        })
      } catch (error) {
        console.error('初始化WebSocket失败:', error)
      }
    },
    
    updateFriendOnlineStatus(userId, isOnline) {
      const friend = this.friends.find(f => f.id === userId)
      if (friend) {
        friend.isOnline = isOnline
        if (isOnline) {
          friend.lastSeen = new Date().toISOString()
        }
      }
    },
    
    markAllFriendsOffline() {
      this.friends.forEach(friend => {
        friend.isOnline = false
      })
    },
    
    refreshOnlineStatus() {
      // 向服务器请求刷新在线状态
      chatService.requestOnlineStatus()
    },
    
    // ========== 连接管理 ==========
    async retryConnection() {
      try {
        await appStateManager.refreshServerStatus()
        if (this.isServerOnline) {
          await this.loadFriends()
        }
      } catch (error) {
        console.error('重试连接失败:', error)
        uni.showToast({ title: '连接失败，请稍后重试', icon: 'none' })
      }
    },
    
    async manualRetryConnection() {
      this.maxAttemptsReached = false
      await this.retryConnection()
    },
    
    // ========== 清理 ==========
    cleanup() {
      if (this.offlineGraceTimer) {
        clearTimeout(this.offlineGraceTimer)
        this.offlineGraceTimer = null
      }
    }
  }
}
</script>

<style scoped>
.friends-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 警告横幅 */
.alert-banner {
  padding: 12rpx 20rpx;
  font-size: 22rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.alert-banner.reconnecting {
  background: #fffbe6;
  color: #8c6d1f;
  border-bottom: 1rpx solid #f0e6cc;
}

.alert-banner.error {
  background: #fff2f0;
  color: #d4380d;
  border-bottom: 1rpx solid #ffccc7;
  justify-content: space-between;
}

.alert-content {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.retry-small-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4rpx;
  padding: 8rpx 16rpx;
  font-size: 20rpx;
}

/* 好友列表 */
.friends-list {
  background: white;
}

.section-title {
  padding: 24rpx 20rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 120rpx 60rpx;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 24rpx;
  opacity: 0.5;
}

.empty-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 40rpx;
}

.empty-action-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx 48rpx;
  font-size: 26rpx;
  font-weight: bold;
}

.btn-text {
  color: white;
}
</style>

